import asyncio
import time

import websockets
from datetime import datetime

async def websocket_client(url, payload=None):
    try:
        async with websockets.connect(url) as websocket:
            print(f"WebSocket connected to {url}")

            if payload:
                # 发送消息
                await websocket.send(payload)
                print(f"Message '{payload}' sent successfully.")

            # 监听消息
            while True:
                message = await websocket.recv()
                formatted_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
                print(formatted_time)
                print(f"Received message from server: {message}")

    except websockets.exceptions.ConnectionClosedOK:
        print("WebSocket connection closed gracefully. Message sent successfully.")
    except Exception as e:
        print(f"WebSocket connection or communication error: {e}")

async def main():
    #url = 'ws://192.168.146.17/gateway/tw-tunnel-server/websocket/globalTrack&drivingTrajectory&super_admin?tokenauthorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI0Yjk1NmVlMjM1ZmI0NzJkOTllMmQ4M2FiZTc0YmIzZiIsImF1ZCI6ImlvYyIsImlzcyI6Im9hdXRoIiwicm5kIjoiejAzMHUwOHMiLCJleHAiOjM4NTk2MDg4MjEsImlhdCI6MTcxMjEyNTE3NH0.6waBppaLAnYWnb0PBzxcHqxBmfK4t1mBANgOGATJ3o4&tenantid=T1000'
    # 生产环境-设备影子
    # url = 'ws://192.168.101.202/gateway/tw-tunnel-server/websocket/monitoring&deviceShadow&super_admin?tokenauthorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI0Yjk1NmVlMjM1ZmI0NzJkOTllMmQ4M2FiZTc0YmIzZiIsImF1ZCI6ImlvYyIsImlzcyI6Im9hdXRoIiwicm5kIjoiejAzMHUwOHMiLCJleHAiOjM4NTk2MDg4MjEsImlhdCI6MTcxMjEyNTE3NH0.6waBppaLAnYWnb0PBzxcHqxBmfK4t1mBANgOGATJ3o4&tenantid=T1000'
    # 生产环境-全域轨迹
    # url = 'ws://192.168.101.202/gateway/tw-tunnel-server/websocket/globalTrack&drivingTrajectory&super_admin?tokenauthorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI0Yjk1NmVlMjM1ZmI0NzJkOTllMmQ4M2FiZTc0YmIzZiIsImF1ZCI6ImlvYyIsImlzcyI6Im9hdXRoIiwicm5kIjoiejAzMHUwOHMiLCJleHAiOjM4NTk2MDg4MjEsImlhdCI6MTcxMjEyNTE3NH0.6waBppaLAnYWnb0PBzxcHqxBmfK4t1mBANgOGATJ3o4&tenantid=T1000'
    # 生产环境- 民生轨迹
    #url ='ws://192.168.101.202/gateway/tw-tunnel-server/websocket/liveHood&drivingTrajectoryDigitalTwin&super_admin?tokenauthorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI0Yjk1NmVlMjM1ZmI0NzJkOTllMmQ4M2FiZTc0YmIzZiIsImF1ZCI6ImlvYyIsImlzcyI6Im9hdXRoIiwicm5kIjoiejAzMHUwOHMiLCJleHAiOjM4NTk2MDg4MjEsImlhdCI6MTcxMjEyNTE3NH0.6waBppaLAnYWnb0PBzxcHqxBmfK4t1mBANgOGATJ3o4&tenantid=T1000'
    url ='ws://192.168.213.20:8765'
    await websocket_client(url)
    # payload = 'hello,world!'
    # await websocket_client(url,payload)

if __name__ == "__main__":
    asyncio.run(main())
